package com.twothreetwo.xmlLoader
{
	import com.twothreetwo.events.URLUtilsEvent;
	import flash.events.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author 232°Studios | Neil Glenister
	 * @link www.232studios.com
	 */
	public class XMLLoader extends URLLoader
	{
		private var _xmlObject:XML;
		
		/**
		 * Used for loading in XML.
		 * @param	url
		 * @see URLUtilsEvent to return XML Object
		 */
		public function loadXML(url:String):void
		{
			this.addEventListener(Event.COMPLETE, passXML);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			this.addEventListener(ErrorEvent.ERROR, generalError);
			this.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			this.load(new URLRequest(url));
		}
		
		private function passXML(e:Event):void 
		{
			this.removeEventListener(Event.COMPLETE, passXML);
			XML.ignoreWhitespace = true; 
			var xml:XML = new XML(e.target.data);
			dispatchEvent(new URLUtilsEvent(URLUtilsEvent.XML_LOADED, true));
		}
		
		/**
		 * Load error events
		 */
		private function securityError(e:SecurityErrorEvent):void
		{
			e.target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			trace("Security error loading xml: " + e.text);
		}
		
		private function generalError(e:ErrorEvent):void
		{
			e.target.removeEventListener(ErrorEvent.ERROR, generalError);
			trace("Error loading xml: " + e.text);
		}
		
		private function loadError(e:IOErrorEvent):void
		{
			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
			trace("XML is currently unavaliable: " + e);
		}
		
		public function get xmlObject():String 
		{
			return _xmlObject;
		}
	}

}